<template>
  <div class="c-bg-white" v-if="themeDetail && feedTop">
    <!-- 头部 -->
    <div class="c-ph24 c-pv30 c-bg-white c-bd-b12">
      <div class="c-fs28 c-fc-xblack c-text-ellipsis2">
        <i class="iconfont theme-fc c-pr8 c-fs28">&#xe6fd;</i>{{themeDetail.themeName}}
      </div>
      <div class="c-mt12 c-fs20 c-fc-gray c-ws-n">{{themeDetail.joinMemberCount | formatTenThousand}}人参与 | 展示日期：{{themeDetail.isShowTime == 1 ? `${themeDetail.showEndTime} 到期`:`长期有效`}}
      </div>
      <div class="c-mt20 c-pt12 c-pb12 c-ph12 c-bg-sgray c-fs22 c-fc-xblack c-br4" v-if="themeDetail.themeIntro != ''">{{themeDetail.themeIntro}}</div>
      <div class="c-mt20 c-br4 c-hh60 c-flex-row c-justify-sb c-aligni-center c-ph12 theme-bg-10 theme-fc c-fs22" v-if="themeDetail.totalTaskCount > 0" @click="handleClickTask">
        <div>
          <i class="iconfont c-fs22">{{themeDetail.taskState == 2 ? `&#xe68a;` : `&#xe644;`}}</i>
          主题任务{{`(${themeDetail.completeTaskCount}/${themeDetail.totalTaskCount})`}}
        </div>
        <div class="c-flex-row c-flex-center" v-if="isShowTaskState">
          {{taskStateMap(themeDetail.taskState)}}
          <i class="iconfont">&#xe635;</i>
        </div>
      </div>
    </div>
    <template v-if="isShowList">
      <!-- list -->
      <circle-common-list :feedList="feedList" :feedTop="feedTop" :selectList="selectList" :playAduioSrc="playAduioSrc" :progress="progress" :selectedName="selectedName" :selectIndex="selectIndex"
        @clickPreviewImage="clickPreviewImage" @clickPlayAudio="clickPlayAudio" @clickShowVideo="clickShowVideo" @handleClickForward="handleClickForward" @like="like"
        @handleClickOperation="handleClickOperation" @getCircleComment="getCircleComment" @getFeedsDetail="getFeedsDetail" @handleClickChangeSelect="handleClickChangeSelect"
        @handleClickCircleIndex="handleClickCircleIndex" @clickGoLiveDetail="clickGoLiveDetail"></circle-common-list>
      <loading-status-tem v-if="(feedTop.hasPermission || feedTop.role == 2)" :dataStatus="dataStatus" noDataText="暂无数据" class="c-bg-white"
        :class="themeDetail.isJoin == true ?'c-pb80':''"></loading-status-tem>
      <div class="c-bg-white" :class="feedTop.hasPermission ? 'c-pb80':'c-pb248'" v-else>
        <template v-if="feedList.length > 0">
          <div class="c-fc-sgray c-fs20 c-textAlign-c c-flex-row c-flex-center c-hh100">加入圈子可查看更多内容哦~~</div>
        </template>
        <loading-status-tem :noData="feedList.length == 0" noDataText="暂无动态"></loading-status-tem>
      </div>
    </template>
    <template v-else>
      <loading-status-tem :noData="themeDetail.joinType == 2" :noDataTextClass="'c-ws-pw c-fs24 c-fc-gray'" :noDataText="`该主题为付费主题${'\n'}需完成支付才能查看内容与发布内容`"></loading-status-tem>
    </template>
    <!-- 音频 -->
    <audio id="audio" @ended="playAudioEnd" class="c-pf c-p-l-100"></audio>
    <!-- 视频 -->
    <video-popup :showVideo="showVideo" @clickCloseVideo="clickCloseVideo" :videoSrc="currentVideoObj.videoSrc"></video-popup>
    <!-- 海报 -->
    <circle-poster ref="circlePoster" :qrcodeImg="qrcodeImg"></circle-poster>
    <!-- 全部评论 -->
    <open-modal class="c-pz100" :openModal='showCircleComment' @closeModal='closeAddAllComment()'>
      <div class="masker-content c-br-tl20 c-br-tr20 c-p c-pb100">
        <div class="c-w100 c-textAlign-c c-fs28 c-lh40 c-pt24 c-fc-xblack c-fw-b c-pb34">全部评论({{currentCommentCount | formatTenThousand}})</div>
        <i class="iconfont c-pa c-p-t30 c-p-r24 c-fc-sgray c-fs20 c-bg-f6 c-ww30 c-hh30 c-lh30 c-textAlign-c c-brp50 c-flex-row c-flex-center" @click="closeAddAllComment()">&#xe8fd;</i>
        <div class="c-maxh760 c-contexty-scroll c-ph24" @scroll="getCommentsModal" id="commentModal">
          <circle-comment @loadMoreComments="loadMoreComments" @getCommentOperation="getCommentOperation" @clickPlayAudio="clickPlayAudio" @clickShowVideo="clickShowVideo"
            @handleClickCircleIndex="handleClickCircleIndex" :comments="comments" :playAduioSrc="playAduioSrc" :progress="progress"></circle-comment>
          <loading-status-tem :pt20="true" :dataStatus="commentDataStatus" noDataText="暂无评论"></loading-status-tem>
        </div>
        <div class="c-pa c-w100 c-p-l0 c-p-b0 c-fc-sgray c-ph40 c-pv24 c-fs24 box-shadow" @click="showAddCommentModal()">
          <i class="iconfont c-mr12">&#xe90e;</i><span>说点什么吧~</span>
        </div>
      </div>
    </open-modal>
    <!-- 添加评论 -->
    <circle-add-comment ref="circleAddComment" class="c-pz101" :showAddComment="showAddComment" :addComment="addComment" :replyInfo="operationComment" @closeAddComment="closeAddComment"
      @sendComment="sendComment" @playAddCommentVideo="playAddCommentVideo"></circle-add-comment>
    <open-modal class="c-pz101" :openModal='showOperaction' @closeModal='showOperaction = false'>
      <div class="c-br-tl20 c-br-tr20 c-pb60 c-ph24 c-text-hidden c-w100 c-bg-sgray">
        <div class="c-w100 c-flex-row c-aligni-center">
          <div class="c-flex-column c-aligni-center c-justify-center c-ww100 c-pv40 c-mr20" @click="addReply">
            <div class="c-ww80 c-hh80 c-flex-row c-aligni-center c-justify-center c-bg-white c-brp50"><i class="iconfont c-fc-xblack c-fs36">&#xe99c;</i></div>
            <div class="c-fs24 c-fc-gray c-w100 c-mt12 c-textAlign-c">回复</div>
          </div>
          <div class="c-flex-column c-aligni-center c-justify-center c-ww100 c-pv40 c-mr20" @click="deleteComment">
            <div class="c-ww80 c-hh80 c-flex-row c-aligni-center c-justify-center c-bg-white c-brp50"><i class="iconfont c-fc-xblack c-fs36">&#xe6b3;</i></div>
            <div class="c-fs24 c-fc-gray c-w100 c-mt12 c-textAlign-c">删除</div>
          </div>
        </div>
        <div class="c-pv24 c-fc-xblack c-fs24 c-textAlign-c c-bg-white" @click="showOperaction = false">取消</div>
      </div>
    </open-modal>
    <!-- 置顶，精华，隐藏 -->
    <open-modal :openModal="showMoreActions" @closeModal="closeMoreActions">
      <div class="c-br-tl20 c-pt40 c-br-tr20 c-text-hidden c-w100 c-bg-sgray">
        <div class="c-w100 c-flex-row c-flexw-wrap c-ph14">
          <template v-for="(item, index) in moreActions">
            <div class="c-flex-column c-aligni-center c-justify-center c-hh138 c-bg-white c-br20 c-mh10 c-mb40 c-ww130" v-if="item.isshow == true"
              @click="getHandleFeeds(item.updateField, item.status, item.circleFeedsId, item.isClick, item.themeId)" :key="index">
              <i class="iconfont c-fs36" :class="[item.icon, item.color]"></i>
              <div class="c-fs24 c-w100 c-mt12 c-textAlign-c" :class="item.fontColor">{{item.title}}</div>
            </div>
          </template>
        </div>
        <div class="c-flex-row c-flex-center c-w100 c-hh80 c-fs24 c-fc-xblack c-bg-white c-mt20" @click="closeMoreActions">取消</div>
      </div>
    </open-modal>
    <!-- 底部 -->
    <div class="c-w100 c-flex-row c-bg-sgray c-ph24 c-pv20 c-pf c-p-b88 c-maxw640" v-if="!themeDetail.hasPermission" @click.stop="handleClickCircleFeed()">
      <div class="c-ww120 c-hh120">
        <img class="c-ww120 c-hh120 c-br4" :src="feedTop.avatar" alt="">
      </div>
      <div class="c-pl20 c-flex-column c-justify-sb c-flex-grow1 c-w0">
        <p class="c-fs28 c-text-ellipsis2 c-fc-xblack">{{feedTop.name}}</p>
        <div class="c-fs20 c-fc-gray c-flex-row c-justify-sb c-aligni-center">
          <div>
            <span>{{feedTop.memberCount | formatTenThousand}}人加入</span> |
            <span>{{feedTop.feedCount | formatTenThousand}}条动态</span>
          </div>
          <div class="c-ww104 c-hh40 theme-bg c-br32 c-fc-white c-fs18 c-flex-row c-flex-center">加入圈子</div>
        </div>
      </div>
    </div>
    <bottom-buy-com :ckFromTitle="'圈子'">
      <!-- joinType1：免费2:付费 -->
      <template>
        <div @click.stop="handleClickJoinCircle()" v-if="themeDetail.isJoin" class="c-flex-column c-justify-center c-aligni-center c-fc-white c-hh64 c-w100 c-br32"
          :class="themeDetail.hasPermission == true ? 'theme-bg':'theme-bg-10'">
          <span class="c-fs28 c-lh">立即参与</span>
        </div>
        <!-- 付费 -->
        <div v-if="themeDetail.joinType == 2 && themeDetail.isJoin == false" class="c-flex-column c-justify-center c-aligni-center c-fc-white c-hh64 c-w100 c-br32"
          :class="themeDetail.hasPermission == true ? 'theme-bg':'theme-bg-10'" @click.stop="clickBuy()">
          <span class="c-fs28 c-lh" v-if="!$isWxAppIos()">{{'￥' | iosPriceFilter}}{{Number(themeDetail.price).toFixed(2)}}立即参与</span>
          <span class="c-fs28 c-lh" v-else>咨询客服</span>
        </div>
      </template>
    </bottom-buy-com>
    <!-- 浮动按钮 -->
    <div v-if="feedTop.hasPermission" class="theme-box-shadow c-pf c-pz1 c-p-b240 c-p-c-216 c-ww70 c-hh70 theme-bg c-flex-row c-justify-center c-aligni-center c-brp50"
      @click="handleClickCircleFeed()">
      <i class="iconfont c-fc-white c-fs34">&#xe6bc;</i>
    </div>
    <!-- 主题任务 -->
    <circle-theme-task-modal :themeId="themeId" :completeTaskCount="themeDetail.completeTaskCount" :totalTaskCount="themeDetail.totalTaskCount" :showTaskModal="showTaskModal"
      @handleClickCloseTask="handleClickCloseTask"></circle-theme-task-modal>
  </div>
</template>

<script>
import { utilJs, wxUtilJs } from "@/utils/common.js";
import circleUtils from '@/utils/circleUtils.js';
import circleCommonList from "@/components/homePage/circle/circleCommonList.vue";
import bottomBuyCom from "@/components/templates/common/bottomBuyCom.vue";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import videoPopup from "@/components/templates/common/videoPopup.vue";
import circlePoster from "@/components/homePage/circle/circlePoster.vue";
import circleThemeTaskModal from "@/components/homePage/circle/circleThemeTaskModal.vue";
import OpenModal from "@/components/templates/common/openModal.vue";
// 评论
import circleComment from "@/components/homePage/circle/circleComment.vue";
import circleAddComment from "@/components/homePage/circle/circleAddComment.vue";
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";

const LIMIT = 10;
let pageIndex = 1;
let page = 1;
// let progressTime;
let commentPage = 1;
let isAddComment = false; // 判断是否是增加评论
let cIndex = 0; // 判断当前评论的索引
let getType = 1; // 评论获取类型 1是正常分页加载 2是操作刷新数据
let isFilterComment = false; // 判断是否删除数据
let childCommentChangeArr = [];
export default {
  name: 'CircleTheme',
  components: {
    circleCommonList,
    bottomBuyCom,
    loadingStatusTem,
    videoPopup,
    circlePoster,
    OpenModal,
    circleComment,
    circleAddComment,
    circleThemeTaskModal
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") || 'mb5_default',
      circleId: "",
      themeId: "",
      themeDetail: null,
      feedTop: null,
      status: 1, //默认正常1，-1拉入黑名单
      isExit: 1, //默认正常1，-1退出圈子
      isNewCircleMaster: -1, //1,新圈主，-1否
      newCircleMasterToast: -1, //-1没弹过，1弹过
      introduce: '', //圈主简介信息
      isShowList: true, //判断是否显示列表
      selectList: [{
        title: '全部',
        index: 0
      }, {
        title: '精选',
        index: 1
      }, {
        title: '置顶',
        index: 2
      }, {
        title: '圈主',
        index: 3
      }],
      // 列表
      dataStatus: 'HAS_MORE_DATA',
      feedList: [],
      selectIndex: 0,
      playAduioSrc: "",
      progress: 0,
      isPlayingAudio: false,
      showVideo: false,
      currentVideoObj: {},
      qrcodeImg: "",
      moreActions: [],
      showMoreActions: false,
      // 评论
      operationComment: null, // 当前操作信息
      currentCommentCount: 0, // 当前评论条数
      circleFeedsId: '', // 当前点击的圈子
      commentDataStatus: 'HAS_MORE_DATA', // 一级评论数据状态
      comments: [], // 全部评论信息
      showAddComment: false, // 添加评论
      addComment: { // 添加评论
        text: '',
        img: []
      },
      showCircleComment: false, // 展示评论
      showOperaction: false, // 展示评论操作
      themeScrollTop: 0, //滚动定位位置
      bindPhoneSetting: null,
      selectedName: '全部',
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      sendCommentFlag: false,
      showTaskModal: false,
      isCanRelease: true,
    }
  },
  created() {
    utilJs.appShare(this);
  },
  deactivated() {
    this.$cjConfirm.hide();
    this.$previewImg.hide();
    window.removeEventListener('scroll', this.windowScrollFunction);
  },
  computed: {
    taskStateMap() {
      return function (state) {
        let stateName = '';
        if (state == 0) {
          stateName = '待完成'
        } else if (state == 1) {
          stateName = '进行中'
        } else if (state == 2) {
          stateName = '已完成'
        }
        return stateName
      }
    },
    isShowTaskState() {
      if (this.feedTop.hasPermission) {
        if (this.themeDetail.isJoin) {
          return true
        } else if (this.themeDetail.joinType == 2 && this.themeDetail.isJoin == false) {
          return false;
        }
      } else {
        return false;
      }
    }
  },
  activated() {
    this.themeId = this.$route.query.themeId || "";
    this.status = 1;
    this.isExit = 1;
    this.isNewCircleMaster = -1;
    this.introduce = '';
    this.selectIndex = 0;
    this.playAduioSrc = "";
    this.progress = 0;
    this.isPlayingAudio = false;
    this.showVideo = false;
    this.currentVideoObj = {};
    this.isShowList = true;
    this.qrcodeImg = "";
    this.moreActions = [];
    this.showMoreActions = false;
    this.selectedName = '全部';
    this.selectList = [{
      title: '全部',
      index: 0
    }, {
      title: '精选',
      index: 1
    }, {
      title: '置顶',
      index: 2
    }, {
      title: '圈主',
      index: 3
    }]
    // 评论
    this.showCircleComment = false;
    this.showAddComment = false;
    this.addComment = {
      text: "",
      img: []
    }
    this.showOperaction = false;
    this.themeScrollTop = sessionStorage.getItem('themeScrollTop') || 0;
    this.sendCommentFlag = false;
    this.showTaskModal = false;
    getBindPhoneSetting(global.ckFrom.circle).then(res => {
      this.bindPhoneSetting = res;
    });
    if (utilJs.checkNeedInitData(this.feedList) || this.themeScrollTop == 0) {
      this.themeDetail = null;
      this.feedTop = null;
      this.getThemeDetails();
    }
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  beforeRouteLeave(to, from, next) {
    this.themeScrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    if (to.path == '/homePage/circle/circleDetail') {
      sessionStorage.setItem('themeScrollTop', this.themeScrollTop);
    } else {
      sessionStorage.removeItem('themeScrollTop');
    }
    next();
  },
  methods: {
    //跳转编辑
    goToEdit(data) {
      let query = {
        id: this.circleId,
        feedsId: data.circleFeedsId,
      }
      if (data.themeId) {
        query.themeId = data.themeId
      }
      this.$routerGo(this, "push", {
        path: "/homePage/circle/circleRelease",
        query: query
      })
    },
    handleClickCloseTask() {
      this.showTaskModal = false;
    },
    handleClickTask() {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      if (this.isCanReleaseFun()) return;
      if (this.isShowList == false) {
        this.$showCjToast({
          text: "暂无主题权限，请先加入主题~",
          type: "warn",
        });
        return true;
      }
      this.showTaskModal = true;
    },
    // 请求访问日志接口
    addVisitLog() {
      utilJs.postMethod(global.apiurl + `circle/addVisitLog`, {
        circleId: this.circleId,
        circleMemberId: this.feedTop.circleMemberId
      }, res => { })
    },
    clickGoLiveDetail(liveId, liveType) {
      let toPath = ''
      if (liveType == 1) {
        toPath = `/homePage/live/livePersonalDetail?liveId=${liveId}`
      } else if (liveType == 2) {
        toPath = `/homePage/live/liveDetail?liveId=${liveId}`;
      } else {
        toPath = `/homePage/privateClass/classDetail?classId=${liveId}`;
      }
      this.$routerGo(this, 'push', {
        path: toPath
      })
    },
    // 进入圈子
    handleClickCircleFeed() {
      this.$routerGo(this, "push", {
        path: "/homePage/circle/circleFeed",
        query: {
          id: this.circleId
        }
      })
    },
    // 购买主题圈子
    clickBuy() {
      if (this.isBindPhone(1)) return;
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      let queryT = null;
      queryT = {
        cId: 0,
        extId: this.themeId,
        ckFrom: global.ckFrom.circleTheme,
        extraId: 0,
      }
      this.$routerGo(this, "push", {
        path: "/homePage/course/coursePay",
        query: queryT
      });
    },
    getFeedsDetail(item, event) {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      if (event.target.className.includes('link')) {
        let href = event.target.outerText;
        utilJs.locationHref(href);
        return;
      } else {
        this.$routerGo(this, "push", {
          path: "/homePage/circle/circleDetail",
          query: {
            circleFeedsId: item.circleFeedsId,
          }
        })
      }
    },
    // 播放添加评论的视频
    playAddCommentVideo(currentVideoObj) {
      if (this.isPlayingAudio == true) {
        this.playAudioEnd();
      }
      this.showVideo = true;
      this.currentVideoObj = currentVideoObj
    },
    // 修改评论的count值
    changeCommentCount(circleFeedsId, count) {
      this.feedList.forEach((item, index) => {
        if (item.circleFeedsId == circleFeedsId) {
          this.$set(this.feedList[index], 'commentCount', count);
        }
      })
    },
    // 删除评论
    deleteComment() {
      let comment = this.operationComment;
      utilJs.getMethod(`${global.apiurl}circle/delCircleComments/${comment.commentId}`, res => {
        this.showOperaction = false;
        this.$showCjToast({
          text: "删除成功",
          type: "success",
        });
        getType = 2;
        if (comment.rootCId == comment.commentId) {
          isFilterComment = true;
          let comments = this.comments.filter(item => item.commentId != comment.commentId);
          this.comments = comments;
        }
        this.getCircleCommentList(this.circleFeedsId);
        let commentCount = (comment.childCommentCount ? comment.childCommentCount : 0) + 1;
        this.currentCommentCount = this.currentCommentCount - commentCount;
        this.changeCommentCount(this.circleFeedsId, this.currentCommentCount);
        circleUtils.togglePoints({ actId: comment.commentId, actType: 2, handleType: 2, sourceType: 5 }, this.circleId, this)
      })
    },
    // 获取操作评论索引
    getCommentOperation(item) {
      this.operationComment = item;
      // 没有删除权限,点击直接回复
      if (item.delPermission) {
        this.showOperaction = true;
      } else {
        this.addReply();
      }
      let cId = item.rootCId;
      this.comments.forEach((cItem, index) => {
        if (cItem.commentId == cId) {
          cIndex = index;
        }
      })
    },
    // 发送评论
    sendComment(comment) {
      if (this.sendCommentFlag) return;
      this.sendCommentFlag = true;
      let data = {
        circleFeedsId: this.circleFeedsId,
        circleId: this.circleId,
        parentId: this.operationComment ? this.operationComment.commentId : 0,
        rootCId: this.operationComment ? this.operationComment.rootCId : 0,
        replyUserId: this.operationComment ? this.operationComment.userId : 0,
        content: comment.text,
        img: comment.img,
        audio: comment.audio,
        audio_time: comment.audio_time,
        video: comment.video,
        grade: this.operationComment ? 2 : 1,
        type: this.operationComment ? 2 : 1,
        fileId: comment.fileId
      }
      utilJs.postMethod(`${global.apiurl}circle/addCircleFeedComments`, data, res => {
        this.$showCjToast({
          text: res.msg,
          type: "success",
        });
        this.sendCommentFlag = false;
        this.showAddComment = false;
        this.currentCommentCount++;
        this.changeCommentCount(this.circleFeedsId, this.currentCommentCount);
        this.getCircleCommentList(this.circleFeedsId);
        if (!this.operationComment) {
          circleUtils.togglePoints({ actId: res.commentId, actType: 2, handleType: 1, sourceType: 5 }, this.circleId, this)
        }
      }, failRes => {
        this.sendCommentFlag = false;
      })
    },
    // 关闭添加评论
    closeAddComment() {
      this.showAddComment = false;
    },
    closeAddAllComment() {
      this.showCircleComment = false;
      getType = 1;
    },
    // 回复评论
    addReply() {
      this.showOperaction = false;
      this.showAddComment = true;
      getType = 2;
      this.$nextTick(() => {
        this.$refs.circleAddComment.$refs.contentArea.focus();
      })
    },
    // 加载更多次级评论列表
    loadMoreComments(index) {
      this.$set(this.comments[index], 'isTotalShow', true);
    },
    // 点击评论
    showAddCommentModal() {
      getType = 2;
      isAddComment = true;
      cIndex = 0;
      this.showAddComment = true;
      this.operationComment = null;
      this.$nextTick(() => {
        this.$refs.circleAddComment.$refs.contentArea.focus();
      })
    },
    // 下拉到底部加载更多
    getCommentsModal(callBack) {
      if (!(this.commentDataStatus == 'HAS_MORE_DATA' && this.comments.length > 0)) {
        return
      }
      let commentModal = document.getElementById('commentModal');
      if (!commentModal) {
        return
      }
      if ((commentModal.scrollHeight - (commentModal.scrollTop + commentModal.clientHeight)) <= 20) {
        this.getCircleCommentList(this.circleFeedsId);
      }
    },
    // 评论去重
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.commentId) && res.set(arr.commentId, 1))
    },
    // 解构评论列表
    commentChange(commentArr) {
      for (let i = 0; i < commentArr.length; i++) {
        if (commentArr[i].isShow == -1) continue;
        commentArr[i].createdAt = utilJs.changeCommentTime(commentArr[i].createdAt);
        childCommentChangeArr.push(commentArr[i]);
        if (commentArr[i].chileComment && commentArr[i].chileComment.length > 0) {
          this.commentChange(commentArr[i].chileComment)
        }
      }
    },
    // 获取评论列表
    getCircleCommentList(circleFeedsId) { // commentType=1一级评论 commentType=2二级评论; getType评论获取类型 1是正常分页加载 2是操作刷新数据
      let showMoreIndex = '';
      if (getType == 1) {
        if (this.commentDataStatus == 'LOADING') {
          return;
        }
        this.commentDataStatus = 'LOADING';
      } else {
        if (this.comments && this.comments[cIndex] && this.comments[cIndex].isTotalShow == true) {
          showMoreIndex = cIndex;
        }
      }
      let page = getType == 1 ? commentPage : parseInt(cIndex / 10) + 1;
      utilJs.getMethod(`${global.apiurl}circle/getCircleFeedComments?circleFeedsId=${circleFeedsId}&commentType=1&parentId=${circleFeedsId}&page=${page}`, res => {
        this.showCircleComment = true;
        let resList = res.data || [];
        if (resList && resList.length > 0) {
          childCommentChangeArr = [];
          for (let i = 0; i < resList.length; i++) {
            resList[i].isTotalShow = false;
            resList[i].createdAt = utilJs.changeCommentTime(resList[i].createdAt);
            if (resList[i].chileComment && resList[i].chileComment.length > 0) {
              this.commentChange(resList[i].chileComment);
              resList[i].replyList = childCommentChangeArr;
              resList[i].childCommentCount = resList[i].replyList.length;
              childCommentChangeArr = [];
            }
            resList[i].childCommentCount = resList[i].replyList ? resList[i].replyList.length : 0;
          }
        }
        if (getType == 2) {
          if (isAddComment && isFilterComment == false) {
            this.comments.unshift(resList[0]);
            isAddComment = false;
          } else if (isAddComment == false && isFilterComment == false && this.comments && this.comments.length > 0) {
            this.$set(this.comments, cIndex, resList[cIndex % 10]);
            if (!(showMoreIndex === '')) {
              this.$set(this.comments[showMoreIndex], 'isTotalShow', true);
              showMoreIndex = '';
            }
          } else if (isFilterComment) {
            isFilterComment = false;
            if (resList && resList.length > 0) this.comments.push(resList[resList.length - 1]);
          }
          getType = 1;
          cIndex = 0;
        } else {
          if (commentPage == 1) {
            this.comments = resList;
          } else {
            this.comments = [...this.comments, ...resList];
          }
          if ((res.total > this.comments.length) && (res.total != 0)) {
            commentPage++;
          }
        }
        if (this.comments && this.comments.length > 0) this.comments = this.unique(this.comments);
        if (res.total == this.comments.length) {
          this.commentDataStatus = res.total == 0 ? "NO_DATA" : "NO_MORE_DATA";
        } else {
          this.commentDataStatus = 'HAS_MORE_DATA';
        }
      }, failRes => {
        this.commentDataStatus = "DATA_ERROR";
      })
    },
    // 获取一级评论
    getCircleComment(circleFeedsId, commentCount) {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      this.operationComment = null;
      this.currentCommentCount = Number(commentCount);
      this.circleFeedsId = circleFeedsId;
      this.commentDataStatus = "HAS_MORE_DATA";
      this.comments = [];
      isAddComment = false;
      isFilterComment = false;
      commentPage = 1;
      cIndex = 0;
      this.getCircleCommentList(this.circleFeedsId);
    },
    closeMoreActions() {
      this.showMoreActions = false;
    },
    // 删除圈子
    delCircleFeed(circleFeedsId) {
      let _this = this;
      utilJs.getMethod(`${global.apiurl}circle/delCircleFeed/${circleFeedsId}`, res => {
        this.showMoreActions = false;
        this.$showCjToast({
          text: "操作成功",
          type: "success",
        })
         _this.initData();
      })
    },
    // 操作圈子置顶，精华，隐藏
    handleFeeds(updateField, status, circleFeedsId) {
      let _this = this;
      utilJs.postMethod(global.apiurl + `circle/handleFeeds/${circleFeedsId}`, {
        updateField: updateField,
        status: status
      }, res => {
        this.showMoreActions = false;
        if (updateField == 'isEssence') {
          //精选操作关联积分
          circleUtils.togglePoints({ actId: circleFeedsId, actType: 1, handleType: status == 1 ? 1 : 2, sourceType: 2 }, this.circleId, this)
        }
        this.$showCjToast({
          text: "操作成功",
          type: "success",
        })
        _this.initData();
      })
    },
    getHandleFeeds(updateField, status, circleFeedsId, isClick, themeId) {
      let _this = this;
      if (isClick == false) {
        return;
      }
      if (updateField == "delete") {
        this.showMoreActions = false;
        this.$cjConfirm({
          title: '确定删除？', //
          titleCenter: true, //标题是否居中
          message: '删除后，发布的内容将无法恢复',
          messageCenter: true, //内容是否居中
          showMasker: true, //是否显示透明背景
          clickCloseModal: false, //是否点击透明背景关闭弹窗
          showCancelButton: true, //是否显示取消按钮
          cancelButtonText: '', //取消按钮文本
          confirmButtonText: '', //确认按钮文本
          onConfirm: () => {
            _this.delCircleFeed(circleFeedsId);
            circleUtils.togglePoints({ actId: circleFeedsId, actType: 1, handleType: status == 1 ? 1 : 2, sourceType: 5 }, this.circleId, this)
          },
          onCancel() {
          },
        })
      } else if (updateField == 'edit') {
        let query = {
          id: this.circleId,
          feedsId: circleFeedsId,
        }
        if (themeId) {
          query.themeId = themeId
        }
        this.$routerGo(this, "push", {
          path: "/homePage/circle/circleRelease",
          query: query
        })
      } else {
        this.handleFeeds(updateField, status, circleFeedsId)
      }
    },
    handleClickOperation(item) {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      // 当我是圈主身份的时候可操作内容
      if (this.feedTop.role == 2) {
        this.moreActions = [
          {
            icon: item.isEssence == 1 ? "icon-yichujingxuan" : "icon-yirujingxuan",
            title: item.isEssence == 1 ? "移出精选" : "移入精选",
            updateField: "isEssence",
            isshow: true,
            isClick: item.status == 1 ? true : false,
            color: item.status == 1 ? 'c-fc-black' : 'c-fc-sgray',
            fontColor: item.status == 1 ? 'c-fc-xblack' : 'c-fc-sgray',
            status: item.isEssence == 1 ? "-1" : "1",
            circleFeedsId: item.circleFeedsId
          }, {
            icon: "icon-zhiding1",
            title: item.isTop == 1 ? "取消置顶" : "置顶",
            updateField: "isTop",
            isshow: true,
            isClick: item.status == 1 ? true : false,
            color: item.status == 1 ? 'c-fc-black' : 'c-fc-sgray',
            fontColor: item.status == 1 ? 'c-fc-xblack' : 'c-fc-sgray',
            status: item.isTop == 1 ? "-1" : "1",
            circleFeedsId: item.circleFeedsId
          }, {
            icon: "icon-yincang1",
            title: item.status == 1 ? "隐藏" : "取消隐藏",
            updateField: "status",
            isshow: true,
            isClick: true,
            color: 'c-fc-black',
            fontColor: 'c-fc-xblack',
            status: item.status == 1 ? "-1" : "1",
            circleFeedsId: item.circleFeedsId
          }, {
            icon: "icon-lajitongxian",
            title: "删除",
            updateField: "delete",
            isshow: item.isSelf,
            isClick: true,
            color: 'c-fc-black',
            fontColor: 'c-fc-xblack',
            circleFeedsId: item.circleFeedsId
          }
        ];
      } else if (this.feedTop.role == 1 && this.feedTop.isAnswer == 1 && this.companyAuth.enableQuestionModule == 1) {
        this.moreActions = [
          {
            icon: item.isEssence == 1 ? "icon-yichujingxuan" : "icon-yirujingxuan",
            title: item.isEssence == 1 ? "移出精选" : "移入精选",
            updateField: "isEssence",
            isshow: this.feedTop.isAllowTopEssence == 1 ? true : false,
            isClick: item.status == 1 ? true : false,
            color: item.status == 1 ? 'c-fc-black' : 'c-fc-sgray',
            fontColor: item.status == 1 ? 'c-fc-xblack' : 'c-fc-sgray',
            status: item.isEssence == 1 ? "-1" : "1",
            circleFeedsId: item.circleFeedsId
          }, {
            icon: "icon-zhiding1",
            title: item.isTop == 1 ? "取消置顶" : "置顶",
            updateField: "isTop",
            isshow: this.feedTop.isAllowTopEssence == 1 ? true : false,
            isClick: item.status == 1 ? true : false,
            color: item.status == 1 ? 'c-fc-black' : 'c-fc-sgray',
            fontColor: item.status == 1 ? 'c-fc-xblack' : 'c-fc-sgray',
            status: item.isTop == 1 ? "-1" : "1",
            circleFeedsId: item.circleFeedsId
          }, {
            icon: "icon-yincang1",
            title: item.status == 1 ? "隐藏" : "取消隐藏",
            updateField: "status",
            isshow: this.feedTop.isAllowHideFeeds == 1 ? true : false,
            isClick: true,
            color: 'c-fc-black',
            fontColor: 'c-fc-gray',
            status: item.status == 1 ? "-1" : "1",
            circleFeedsId: item.circleFeedsId
          }, {
            icon: "icon-lajitongxian",
            title: "删除",
            updateField: "delete",
            isshow: item.isSelf,
            isClick: true,
            color: 'c-fc-black',
            fontColor: 'c-fc-xblack',
            circleFeedsId: item.circleFeedsId
          }
        ];
      } else if (this.feedTop.hasPermission && item.isSelf == true) {
        this.moreActions = [
          {
            icon: "icon-lajitongxian",
            title: "删除",
            updateField: "delete",
            isshow: true,
            circleFeedsId: item.circleFeedsId
          }
        ]
      }
      if (item.isSelf == true && !item.questionDetailId) {
        //动态是自己
        this.moreActions.push({
          icon: "icon-bianji",
          title: "编辑",
          updateField: "edit",
          color: 'c-fc-black',
          fontColor: 'c-fc-xblack',
          isshow: true,
          circleFeedsId: item.circleFeedsId,
          themeId: item.themeId
        });
      }
      this.showMoreActions = true;
    },
    // 点赞
    like(index) {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      if (this.feedList[index].isZans) {
        this.feedList[index].isZans = false;
        this.feedList[index].likeCount--;
        this.addZans(this.feedList[index].circleFeedsId);
        circleUtils.togglePoints({ actId: this.feedList[index].circleFeedsId, actType: 1, handleType: 2, sourceType: 6 }, this.circleId, this)
      } else {
        this.feedList[index].isZans = true;
        this.feedList[index].likeCount++
        this.addZans(this.feedList[index].circleFeedsId);
        circleUtils.togglePoints({ actId: this.feedList[index].circleFeedsId, actType: 1, handleType: 1, sourceType: 6 }, this.circleId, this)
      }
    },
    // 触发点赞接口
    addZans(circleFeedsId) {
      utilJs.postMethod(global.apiurl + `circle/addZans/${this.circleId}`, {
        circleFeedsId: circleFeedsId,
      }, res => { })
    },
    // 转发圈子
    handleClickForward(item) {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      this.getFeedsQRCode(item)
    },
    // 转发生成图片
    getFeedsQRCode(item) {
      let circleFeedsId = item.circleFeedsId;
      utilJs.getMethod(`${global.apiurl}circle/getFeedsQRCode/${circleFeedsId}`, res => {
        this.qrcodeImg = "data:image/svg+xml;base64," + window.btoa(decodeURIComponent(encodeURIComponent(res.qrCodeUrl)))
        this.$refs.circlePoster.handleClickPoster(item);
      })
    },
    //点击关闭视频
    clickCloseVideo() {
      if (this.showVideo) {
        this.showVideo = false;
      }
    },
    clickShowVideo(videoSrc) {
      if (this.isPlayingAudio == true) {
        this.playAudioEnd();
      }
      this.showVideo = true;
      this.currentVideoObj = { videoSrc }
    },
    //监听音频播放结束执行的内容
    playAudioEnd() {
      //播放结束自动播放下一个非自己发的语音并且非已读语音
      this.playAduioSrc = "";
      this.progress = 0;
      document.getElementById("audio").src = this.playAduioSrc;
      this.isPlayingAudio = false;
    },
    // 播放音频
    clickPlayAudio(audioUrl, audioTime) {
      let audio = document.getElementById("audio");
      if (this.playAduioSrc == audioUrl) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        return;
      }
      this.playAduioSrc = audioUrl;
      this.progress = 0;
      //返回mp3则用audio播放，否则将使用微信将文件下载然后播放
      if (this.playAduioSrc.includes("http") || !this.playAduioSrc) {
        document.getElementById("audio").src = this.playAduioSrc;
        audio.play();
        audio.removeEventListener("ended", this.playAudioEnd, false);
        audio.addEventListener("ended", this.playAudioEnd, false);
        // let progressIndex = 0;
        // progressTime = setInterval(() => {
        //   progressIndex++;
        //   if (audioTime - progressIndex >= 0) {
        //     this.progress = (100 / audioTime) * progressIndex;
        //   } else {
        //     clearInterval(progressTime)
        //   }
        // }, 1000)
      }
      this.isPlayingAudio = true;
    },
    // 点击图片放大预览
    clickPreviewImage(imgUrl, itemImgList, imgIndex) {
      if (!imgUrl) {
        return;
      }
      let imgUrlList = [];
      for (let key of itemImgList) {
        if (key) {
          imgUrlList.push(key);
        }
      }
      // this.$previewImg({
      //   activeIndex: imgIndex,
      //   imgList: imgUrlList
      // })
      wxUtilJs.previewImage({
        current: imgUrl, // 当前显示图片的http链接
        urls: imgUrlList // 需要预览的图片http链接列表
      });
    },
    // 参加免费主题
    handleClickJoinCircle() {
      if (this.isBindPhone(2)) return;
      if (this.isSignOut()) return;
      if (this.isHasPermission()) return;
      if (this.isCanReleaseFun()) return;
      this.$routerGo(this, "push", {
        path: "/homePage/circle/circleRelease",
        query: {
          id: this.circleId,
          themeId: this.themeId
        }
      })
    },
    // 判断是否绑定手机号码
    isBindPhone(bindType) {
      if ((this.bindPhoneSetting && this.bindPhoneSetting.buyBind && bindType == 1) || (this.bindPhoneSetting && this.bindPhoneSetting.getBind && bindType == 2)) {
        if (utilJs.goBindMobile()) return true;
      } else {
        return false;
      }
    },
    // 判断身份是否可以发布动态
    isRelease() {
      return new Promise((resolve, reject) => {
        utilJs.getMethod(`${global.apiurl}circle/getIsCanRelease/${this.circleId}`,
          res => {
            resolve(res);
          },
          failRes => {
            reject(failRes)
          }
        )
      })
    },
    // 判断是否有身份权限
    isCanReleaseFun() {
      if (this.isCanRelease == false) {
        this.$showCjToast({
          text: "您暂无权限发布内容，请联系圈子管理员~",
          type: "warn",
        });
        return true;
      } else {
        return false;
      }
    },
    // 判断是否有权限
    isHasPermission() {
      // role：1=成员；2=圈主  status：1=正常；-1=拉入黑名单  isExit:1=正常；-1=退出了圈子
      if (this.feedTop.hasPermission == false && this.status == 1) {
        this.$showCjToast({
          text: "加入圈子可参与互动",
          type: "warn",
        });
        return true;
      } else if (this.feedTop.hasPermission == false && this.status == -1) {
        this.$showCjToast({
          text: "暂无此操作权限，请联系圈子管理员~",
          type: "warn",
        });
        return true;
      } else if (this.feedTop.isExit == -1) {
        this.$showCjToast({
          text: "暂无此操作权限，请联系圈子管理员~",
          type: "warn",
        });
        return true;
      } else {
        return false;
      }
    },
    isSignOut() {
      // 黑名单
      if (this.status == -1) {
        this.$showCjToast({
          text: "暂无此操作权限，请联系圈子管理员~",
          type: "warn",
        });
        return true;
      } else {
        return false;
      }
    },
    getThemeDetails() {
      utilJs.getMethod(`${global.apiurl}circle/getThemeDetails?themeId=${this.themeId}`, res => {
        if (res.isShow == false) {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "circle",
              info: '主题已下架或不可展示'
            }
          });
          return
        }
        this.themeDetail = res;
        this.themeId = res.themeId;
        this.circleId = res.circleId;
        setDocumentTitle(res.themeName || "主题名称");
        // 当为付费模式
        if (res.joinType == 2 && res.isJoin == false) {
          this.isShowList = false;
        }
        this.getDetails(1);
        this.initData();
        this.isRelease().then(res => {
          this.isCanRelease = res.isCanRelease;
        })
      }, failRes => {
        this.$routerGo(this, "replace", {
          path: "/error/emptyPage",
          query: {
            from: "circle",
            info: failRes.msg
          }
        });
      })
    },
    // 转移圈子弹窗
    updateNewCircleMasterToast() {
      utilJs.postMethod(`${global.apiurl}circle/updateNewCircleMasterToast`, {
        circleId: this.circleId
      }, res => {

      })
    },
    // 获取接口数据
    getDetails(type) {
      let _this = this;
      utilJs.getMethod(`${global.apiurl}circle/details/${this.circleId}?type=${type}`, res => {
        if (res.deletedStatus == -1) {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "circle",
              info: '该圈子已被删除,请联系管理员'
            }
          });
          return
        }
        if (res.isShow == -1) {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "circle",
              info: '该圈子已被隐藏,请联系管理员'
            }
          });
          return
        }
        this.feedTop = res;
        this.status = res.status || 1;//圈子黑名单1，正常，-1拉入黑名单
        this.isExit = res.isExit || 1;//圈子1正常，-1退出圈子
        this.isNewCircleMaster = res.isNewCircleMaster;
        this.newCircleMasterToast = res.newCircleMasterToast;
        this.introduce = res.introduce;
        // if (res.enableQuestion == 1 && this.companyAuth.enableQuestionModule == 1 && res.hasPermission == true) {
        //   this.selectList.push({title: "问答", index: 4})
        // }
        // 判断为是否成为新圈主弹窗
        if (this.isNewCircleMaster == 1 && this.newCircleMasterToast == -1) {
          if (this.introduce != null && this.introduce != '') {
            // 存储是否成为新圈主
            this.$cjConfirm({
              title: '提示', //
              titleCenter: true, //标题是否居中
              message: '您已成为该圈子的新圈主，赶快去看看成员都在关注什么吧',
              messageCenter: true, //内容是否居中
              showMasker: true, //是否显示透明背景
              clickCloseModal: false, //是否点击透明背景关闭弹窗
              showCancelButton: false, //是否显示取消按钮
              cancelButtonText: '', //取消按钮文本
              confirmButtonText: '', //确认按钮文本
              onConfirm() {
              },
              onCancel() {
              },
            })
          } else {
            // 存储是否成为新圈主
            this.$cjConfirm({
              title: '', //
              titleCenter: true, //标题是否居中
              message: '您已成为该圈子的新圈主，赶快去设置圈主简介吧',
              messageCenter: true, //内容是否居中
              showMasker: true, //是否显示透明背景
              clickCloseModal: false, //是否点击透明背景关闭弹窗
              showCancelButton: true, //是否显示取消按钮
              cancelButtonText: '暂不填写', //取消按钮文本
              confirmButtonText: '去设置', //确认按钮文本
              onConfirm() {
                _this.$routerGo(_this, "push", {
                  path: "/homePage/circle/circleData",
                  query: {
                    circleId: _this.feedTop.circleId
                  }
                })
              },
              onCancel() {
              },
            })
          }
          this.updateNewCircleMasterToast();
        }
        if (this.feedTop.role != 0) {
          this.addVisitLog()
        }
        _this.wechatShare();
      })
    },
    initData() {
      pageIndex = 1;
      page = 1;
      commentPage = 1
      this.dataStatus = 'HAS_MORE_DATA';
      this.commentDataStatus = "HAS_MORE_DATA";
      this.feedList = [];
      document.documentElement.scrollTop = 0;
      this.getFeedsList(this.selectIndex);
      sessionStorage.removeItem('themeScrollTop');
    },
    handleClickChangeSelect(item, index) {
      this.selectIndex = index;
      this.selectedName = item.title;
      this.initData();
    },
    handleClickCircleIndex(item) {
      if (this.isHasPermission()) return;
      if (this.isSignOut()) return;
      this.$routerGo(this, "push", {
        path: "/homePage/circle/circleIndex",
        query: {
          circleId: this.circleId,
          circleMemberId: item.circleMemberId
        }
      })
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.feedList.length > 0) {
          this.getFeedsList(this.selectIndex);
        }
      });
    },
    // 获取动态列表
    getFeedsList(searchType) {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}circle/getFeedsList/${this.circleId}?themeId=${this.themeId}&index=${pageIndex}&searchType=${searchType}&page=${page}&limit=${LIMIT}`, res => {
        let resData = res;
        if (resData && resData.length > 0) {
          for (let i = 0; i < resData.length; i++) {
            resData[i].createdAt = utilJs.changeCommentTime(resData[i].createdAt);
          }
        }
        if (pageIndex == 1) {
          this.feedList = res.data;
        } else {
          this.feedList = [...this.feedList, ...res.data];
        }
        if (res.total * 1 == this.feedList.length) {
          this.dataStatus = res.total * 1 == 0 ? "NO_DATA" : "NO_MORE_DATA";
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          pageIndex += LIMIT;
          page++;
        }
      }, failRes => {
        this.dataStatus = "DATA_ERROR";
      })
    },
    //分享
    wechatShare: function () {
      let title = this.themeDetail.themeName || window.localStorage.getItem("shareTitle");
      let shareImg = this.feedTop.avatar || window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}&themeId=${this.themeId}`;
      let shareDesc = this.themeDetail.themeIntro || '点击查看详情';
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare: function () {
      let title = this.themeDetail.themeName || window.localStorage.getItem("shareTitle");
      let shareImg = this.feedTop.avatar || window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}&themeId=${this.themeId}`;
      let shareDesc = this.themeDetail.themeIntro || '点击查看详情';
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  },

}
</script>

<style lang="less" scoped>
.masker-content {
  background-color: #fff;
  width: 100%;
}
.box-shadow {
  box-shadow: 0px -1px 0px 0px rgba(245, 247, 250, 0.5);
}
</style>